package com.njitzx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.njitzx.en.OrderEnum;
import com.njitzx.entity.dto.OrderPageDTO;
import com.njitzx.entity.po.Order;
import com.njitzx.entity.vo.OrderDetailVO;
import com.njitzx.entity.vo.OrderPageVO;
import com.njitzx.entity.vo.OrderVO;
import com.njitzx.entity.vo.SocketVO;
import com.njitzx.mapper.OrderMapper;
import com.njitzx.service.OrderService;
import com.njitzx.util.HttpClientUtil;
import com.njitzx.websocket.WebSocketServer;
import okhttp3.Headers;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 周鑫
 * @since 2024-08-20
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final WebSocketServer webSocketServer;

    /**
     * 订单表分页查询
     *
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public OrderPageVO findPage(OrderPageDTO orderPageDTO) {
        System.out.println(orderPageDTO);
        Integer pageNum = orderPageDTO.getPageNum();
        Integer pageSize = orderPageDTO.getPageSize();
        PageHelper.startPage(pageNum, pageSize);

        List<OrderVO> orderList = orderMapper.selectByPage(orderPageDTO);

        PageInfo<OrderVO> pageInfo = new PageInfo<>(orderList);


        OrderPageVO pageVO = new OrderPageVO();
        pageVO.setOrders(pageInfo.getList());
        pageVO.setPageNum(pageInfo.getPageNum());
        pageVO.setTotal((int) pageInfo.getTotal());
        return pageVO;
    }


    /**
     * 根据主键查询订单表
     *
     * @param orderId
     * @return
     */
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public List<OrderDetailVO> findById(Integer orderId) {
        return orderMapper.selectVideoDetailById(orderId);
    }

    /**
     * 订单表新增
     *
     * @param order
     */
    @Override
    public void add(Order order) {
        orderMapper.insert(order);
    }

    /**
     * 修改订单表
     *
     * @param order
     */
    @Override
    public void modify(Order order) {
        orderMapper.update(order);
    }

    /**
     * 根据主键删除订单表
     *
     * @param orderId
     */
    @Override
    public void removeById(Serializable orderId) {
        if (((String) orderId).contains(",")) {
            orderMapper.deleteByIds(((String) orderId).split(","));
        } else {
            orderMapper.deleteById(orderId);
        }
    }

    @Override
    public void modifyStatus(Integer orderId, Integer status) {
        Order order = new Order();
        order.setOrderId(orderId);
        order.setStatus(status);
        orderMapper.update(order);
    }

    @Override
    public void sendOrder(Integer orderId, String no) {
        Order order = new Order();
        order.setOrderId(orderId);
        order.setStatus(Integer.parseInt(OrderEnum.RECEIVE.getCode()));
        order.setLogisticsNo(no);
        order.setSendTime(LocalDateTime.now());
        order.setIsSend("是");
        orderMapper.update(order);
    }

    @Override
    public void modifyAddress(Integer orderId, String address) {
        Order order = new Order();
        order.setOrderId(orderId);
        order.setConsigneeAddr(address);
        orderMapper.update(order);
    }

    @Override
    public Order selectByOrderNumber(String tradeNo) {
        return orderMapper.selectByOrderNumber(tradeNo);
    }

    @Override
    public JSONArray queryOrder(String no) {
        String host = "https://wuliu.market.alicloudapi.com";// 【1】请求地址 支持http 和 https 及 WEBSOCKET
        String path = "/kdi";  // 【2】后缀
        String appcode = "d8f2c04f1ca34c7c942fbe7b5396d303";
        String url = host + path;
        Map<String, String> params = new HashMap<>();
        params.put("no", no);
        Header header = new BasicHeader("Authorization", "APPCODE " + appcode);
        Header[] headers = new Header[]{header};
        String body = HttpClientUtil.doGet(url, params, headers);
        JSONObject jsonObject = JSONObject.parseObject(body);
        JSONArray data = jsonObject.getJSONObject("result").getJSONArray("list");
        return data;
    }

    @Override
    public void reminder(Integer orderId) {
        Order order = orderMapper.selectById(orderId);
        SocketVO socketVO = new SocketVO();
        socketVO.setType(1);
        socketVO.setOrderId(orderId);
        socketVO.setOrderNumber(order.getOrderNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(socketVO));
    }
}
